package com.daxt.controller.sysarchives;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;

import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.service.ArchivesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.sys.ArchivesFondsMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.model.service.archives.param.SortCol;
import com.daxt.model.service.archives.vo.ArchivesFonds;
import com.daxt.model.service.archives.vo.ArchivesType;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "全宗管理")
@RestController
public class ArchivesFondsController {

    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private RedisUtil redisUtil;


    @ApiOperation(value = "获取全宗列表", notes = "")
    @GetMapping("/archivesFonds")
    @LoginAuth()
    public Result<List<ArchivesFonds>> list(@ApiIgnore @LoginUser UserInfo loginUser) {
        QueryWrapper<ArchivesFonds> queryWrapper = new QueryWrapper<ArchivesFonds>();

        if(!"admin".equals(loginUser.getUsername()) && !"超级管理员".equals(loginUser.getRole())){
            queryWrapper.eq(loginUser.getFondsId()!=null,"id",loginUser.getFondsId());
        }

        queryWrapper.orderByAsc("sort");
        List<ArchivesFonds> info = archivesFondsMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, info);
    }

    @ApiOperation(value = "添加全宗", notes = "")
    @PostMapping("/archivesFonds")
    public Result<String> save(@RequestBody @Valid ArchivesFonds entity) {

//		if(StringUtils.isEmpty(entity.getFondsName()))return ResultUtil.error("名称不能为空");
        int count = archivesFondsMapper.selectCount(new QueryWrapper<ArchivesFonds>().eq("fondsName", entity.getFondsName()));
        if (count > 0) return ResultUtil.error("触发唯一规则");

        if (StringUtils.isNotEmpty(entity.getFondsNum())) {
            int countNum = archivesFondsMapper.selectCount(new QueryWrapper<ArchivesFonds>().eq("fondsNum", entity.getFondsNum()));
            if (countNum > 0) return ResultUtil.error("触发唯一规则");
        }

        if (entity.getSort() == null) entity.setSort(1);
        int rows = archivesFondsMapper.insert(entity);
        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
    }

    @ApiOperation(value = "修改全宗", notes = "")
    @PutMapping("/archivesFonds")
    public Result<String> edit(@RequestBody @Valid ArchivesFonds entity) {

        int count = archivesFondsMapper.selectCount(new QueryWrapper<ArchivesFonds>().eq("fondsName", entity.getFondsName())
                .notIn("id", entity.getId()));
        if (count > 0) return ResultUtil.error("触发唯一规则");

        if (StringUtils.isNotEmpty(entity.getFondsNum())) {
            int countNum = archivesFondsMapper.selectCount(new QueryWrapper<ArchivesFonds>().eq("fondsNum", entity.getFondsNum())
                    .notIn("id", entity.getId()));
            if (countNum > 0) return ResultUtil.error("触发唯一规则");
        }


//        Object object = redisUtil.get("edit:" + entity.getId());
//        String ckTenantId = "";
//        if (object != null)
//            ckTenantId = object.toString();
//        if (StringUtils.isEmpty(ckTenantId)) {
//            redisUtil.set("edit:" + entity.getId(), entity.getId(), 60 * 10);
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "全宗号ID修改后影响很大，确认修改请重新提交！！！", null);
//        }
        if (entity.getSort() == null)
            entity.setSort(1);
        ArchivesFonds target = new ArchivesFonds();
        BeanUtils.copyProperties(entity, target);
        int rows = archivesFondsMapper.updateById(entity);
//        ArchivesFonds target = new ArchivesFonds();
//        BeanUtils.copyProperties(entity, target);
//        int rows = archivesFondsMapper.updateById(target);
        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
    }

    @ApiOperation(value = "删除全宗", notes = "")
    @DeleteMapping("/archivesFonds")
    public Result<String> del(@RequestBody @Valid @NotEmpty List<String> ids) {
        List<ArchivesFonds> selectBatchIds = archivesFondsMapper.selectBatchIds(ids);
        boolean flag = false;
        for (ArchivesFonds archivesFonds : selectBatchIds) {
            QueryWrapper<ArchivesType> queryWrapper = new QueryWrapper<ArchivesType>();
            queryWrapper.eq("fondsId", archivesFonds.getId());
            List<ArchivesType> selectList = archivesTypeMapper.selectList(queryWrapper);
            if (selectList != null && selectList.size() > 0) {
                flag = true;
            }
        }
        if (flag)
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "先删除全宗下的门类！！！", null);
        int rows = archivesFondsMapper.deleteBatchIds(ids);
        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
    }

    @ApiOperation(value = "全宗排序", notes = "")
    @PostMapping("/archivesFonds/fonds/sort")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> sort(@RequestBody List<SortCol> sortCols) {
        try {
            if (sortCols != null && sortCols.size() > 0) {
                for (SortCol sortCol : sortCols) {
                    ArchivesFonds entity = new ArchivesFonds();
                    entity.setId(Long.parseLong(sortCol.getId()));
                    entity.setSort(sortCol.getSort());
                    archivesFondsMapper.updateById(entity);
                }
            }
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "排序异常", null);
        }
    }


    public String createTenantId(String tenantId) {
        int i = 0;
        for (; i < tenantId.split("").length; i++) {
            if (!tenantId.split("")[i].equals("0")) {
                break;
            }
        }
        String newId = (Integer.parseInt(tenantId.substring(i)) + 1) + "";
        int j = (8 - newId.length());
        for (int k = 0; k < j; k++) {
            newId = "0" + newId;
        }
        return newId;

    }


}
